//
//  FruitsViewController.m
//  FruitsAndHealthy
//
//  Created by appying_wxj on 14/11/11.
//  Copyright (c) 2014年 appying_wxj. All rights reserved.
//

#import "FruitsViewController.h"
#import "DetailContentViewController.h"
#import "MJRefresh.h"// 下拉刷新
#import "AllRequest.h"
#import "UIImageView+ASIRequest.h"
@interface FruitsViewController ()

@end

@implementation FruitsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   // self.title = @"水果分类";
    
    self.titleLab.text = @"水果功效";
    
    [self.navigationController setNavigationBarHidden:YES];// 隐藏系统的导航条
    
    self.view.userInteractionEnabled = YES;
    self.view.backgroundColor = [UIColor colorWithRed:0.9 green:0.69 blue:0.65 alpha:1];
    
   [self initUIFruits];
    
    // 网络请求
    if ([AllRequest checkNet]) {
        [MBProgressHUD showHUDAddedTo:self.fruitsTableView animated:YES];
        [self getAllDate];
        [self.fruitsTableView reloadData];
        [MBProgressHUD hideHUDForView:self.fruitsTableView animated:YES];
    }
}
-(void)initUIFruits{

    // 导航条左边的按钮
    [self.leftButton addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    
    _fruitsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreen_Width, kScreen_Height-64) style:UITableViewStylePlain];
    _fruitsTableView.backgroundColor = [UIColor whiteColor];
    _fruitsTableView.delegate = self;
    _fruitsTableView.dataSource = self;
    _fruitsTableView.rowHeight = 90;
    _fruitsTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _fruitsTableView.separatorStyle = NO;
    [self.view addSubview:_fruitsTableView];
    [self setExtraCellLineHidden:_fruitsTableView];
    
    // 2.集成刷新控件
    [self setupRefresh];
}
// 获取数据
-(void)getAllDate{
//    _effectArray;         // 功效的数组
//    _fitCrowdArray;       // 适合人群的数组
//    _fruitsDetailArray;   // 介绍水果的数组
//    _usageAmountArray;    // 适用量的数组
//    _sweetHintArray;      // 温馨提示的数组
    _contentArray = [[NSMutableArray alloc] initWithCapacity:0];
    _fruitsNameArray = [[NSMutableArray alloc] initWithCapacity:0];
    _detailArray = [[NSMutableArray alloc] initWithCapacity:0];
    _englishArray = [[NSMutableArray alloc] initWithCapacity:0];
    _contentsArray = [[NSMutableArray alloc] initWithCapacity:0];
    _imageArray = [[NSMutableArray alloc] initWithCapacity:0];
    
    _effectArray = [[NSMutableArray alloc] initWithCapacity:0];
    _fitCrowdArray = [[NSMutableArray alloc] initWithCapacity:0];
    _fruitsDetailArray = [[NSMutableArray alloc] initWithCapacity:0];
    _usageAmountArray = [[NSMutableArray alloc] initWithCapacity:0];
    _sweetHintArray = [[NSMutableArray alloc] initWithCapacity:0];
    
    
    AVQuery *fruits = [AVQuery queryWithClassName:@"fruitSpecies"];
    [fruits findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {// 获取数据成功
            _contentArray = [NSMutableArray arrayWithArray:objects];
            for (int i = 0; i < _contentArray.count; i++) {
                AVObject *fruitsName = [_contentArray objectAtIndex:i];
                [_fruitsNameArray addObject:[fruitsName objectForKey:@"fruitsName"]];
                [_detailArray addObject:[fruitsName objectForKey:@"introduction"]];
                [_contentsArray addObject:[fruitsName objectForKey:@"contents"]];
                [_englishArray addObject:[fruitsName objectForKey:@"englishName"]];
                [_imageArray addObject:[fruitsName objectForKey:@"fruitImage"]];
                [_effectArray addObject:[fruitsName objectForKey:@"effect"]];
                [_fitCrowdArray addObject:[fruitsName objectForKey:@"fitCrowd"]];
                [_fruitsDetailArray addObject:[fruitsName objectForKey:@"fruitsDetail"]];
                [_usageAmountArray addObject:[fruitsName objectForKey:@"usageAmount"]];
                [_sweetHintArray addObject:[fruitsName objectForKey:@"sweetHint"]];
                
                
            }
            [_fruitsTableView reloadData];
        } else {// 请求数据失败
            // Log details of the failure
//            NSLog(@"Error: %@ %@", error, [error userInfo]);
        }
    }];
}
/**
 *  集成刷新控件
 */
- (void)setupRefresh {
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_fruitsTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    // 自动刷新(一进入程序就下拉刷新)
    //[self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_fruitsTableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    _fruitsTableView.headerPullToRefreshText = @"下拉可以刷新了";
    _fruitsTableView.headerReleaseToRefreshText = @"松开马上刷新了";
    _fruitsTableView.headerRefreshingText = @"正在刷新中";
    
    _fruitsTableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    _fruitsTableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    _fruitsTableView.footerRefreshingText = @"正在加载中";
}
#pragma mark 开始进入刷新状态
// 下拉刷新
- (void)headerRereshing {
//    // 1.添加数据
//    for (int i = 0; i<5; i++) {
////        [self.fakeData insertObject:[self string] atIndex:0];
//        [self getAllDate];
//    }
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [_fruitsTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_fruitsTableView headerEndRefreshing];
    });
}
// 上提加载
- (void)footerRereshing {
    // 1.添加假数据
//    for (int i = 0; i<5; i++) {
////        [_fruitsTableView addObject:[self string]];
//        [self getAllDate];
//    }
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [_fruitsTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_fruitsTableView footerEndRefreshing];
    });
}

//隐藏表格多余分割线
- (void)setExtraCellLineHidden: (UITableView *)tableView {
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    [tableView setTableHeaderView:view];
}

#pragma mark------UITableViewDataSource  delegate----
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_fruitsNameArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identify = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
    }
    else{
        while ([cell.contentView.subviews lastObject]!=nil) {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    // 分割的线
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 90)];
   
    [cell.contentView addSubview:bgView];

    
    UIImageView *cellImage  = [[UIImageView alloc] initWithFrame:CGRectMake(10, 15, kScreen_Width-20, 75)];
    cellImage.image = [UIImage imageNamed:@"image_danyuange@2x"];
    cellImage.userInteractionEnabled = YES;
    [bgView addSubview:cellImage];

    if (indexPath.row<_contentArray.count) {
        
        
        UIImageView *fruitsImage = [[UIImageView alloc] initWithFrame:CGRectMake(13, 18, 72, 70)];
        fruitsImage.image = [UIImage imageNamed:@"image_xiaokuang@2x"];
        [cell.contentView addSubview:fruitsImage];
        
        // 图片的获取
        AVFile *applicantResume = [_imageArray objectAtIndex:indexPath.row];
        NSString *string = applicantResume.url;
        UIImageView *userImage = [[UIImageView alloc] initWithFrame:CGRectMake(14, 19, 69, 68)];
        userImage.userInteractionEnabled = YES;
        [userImage loadImageFromURL:string showLoadingImg:@"image_zhanwei@2x"];
        [cell.contentView addSubview:userImage];
        
        // 水果的名字
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 20, 150, 25)];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.text = [_fruitsNameArray objectAtIndex:indexPath.row];
        titleLabel.textColor = [UIColor colorWithRed:0.66 green:0.73 blue:0 alpha:1];
        titleLabel.font = [UIFont systemFontOfSize:22];
        titleLabel.textAlignment = NSTextAlignmentLeft;
        [cell.contentView addSubview:titleLabel];
        
        // 水果的一英文名字
        UILabel *englishName = [[UILabel alloc] initWithFrame:CGRectMake(100, 45, kScreen_Width-120, 15)];
        englishName.backgroundColor = [UIColor clearColor];
        englishName.text = [_englishArray objectAtIndex:indexPath.row];
        englishName.textColor = [UIColor colorWithRed:0.76 green:0.85 blue:0 alpha:1];
        englishName.font = [UIFont systemFontOfSize:12];
        englishName.textAlignment = NSTextAlignmentLeft;
        [cell.contentView addSubview:englishName];
        
        // 水果的介绍内容
        UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 65, kScreen_Width-120, 20)];
        contentLabel.backgroundColor = [UIColor clearColor];
        contentLabel.text = [_contentsArray objectAtIndex:indexPath.row];
        contentLabel.textColor = [UIColor colorWithRed:0.31 green:0.28 blue:0 alpha:1];
        contentLabel.font = [UIFont systemFontOfSize:16];
        contentLabel.textAlignment = NSTextAlignmentLeft;
        [cell.contentView addSubview:contentLabel];
        
        
        }
        return cell;

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    dispatch_async(dispatch_get_main_queue(), ^
                   {
                       DetailContentViewController *detail = [[DetailContentViewController alloc] init];
                       detail.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                       detail.detailContent = [_detailArray objectAtIndex:indexPath.row];
                       detail.detailTitle = [_fruitsNameArray objectAtIndex:indexPath.row];
                       detail.effectTitle = [_effectArray objectAtIndex:indexPath.row];
                       detail.fruitsDetailTitle = [_fruitsDetailArray objectAtIndex:indexPath.row];
                       detail.fitCrowdTitle = [_fitCrowdArray objectAtIndex:indexPath.row];
                       detail.usageAmountTitle = [_usageAmountArray objectAtIndex:indexPath.row];
                       detail.sweetHintTitle = [_sweetHintArray objectAtIndex:indexPath.row];
                       [self presentViewController:detail animated:YES completion:nil];
                       
                   });
}

#pragma mark--------ButtonClick------
// 导航条上返回按钮的点击事件
-(void)btnClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
